// plugin
// two components

let Vue

class KVueRouter {
  constructor (options) {
    this.$options = options
    const hashInitial = '/'
    Vue.util.defineReactive(this, 'current', hashInitial)

    // monitor hash change
    window.addEventListener('hashchange', () => {
      this.current = window.location.hash.slice(1)
    })
  }
}

KVueRouter.install = function (_Vue) {
  Vue = _Vue
  // mount $router

  Vue.mixin({
    beforeCreate () {
      // this handler is called when the component is created
      if (this.$options.router) {
        // this indicate it is the root instance
        Vue.prototype.$router = this.$options.router
      }
      Vue.component('vue-routerlink', {
        props: {
          to: {
            type: String,
            required: true
          }
        },
        render (h) {
          return h('a', {attrs: {href: '#' + this.to}}, this.$slots.default)
        }
      })
      Vue.component('vue-routerview', {
        render (h) {
          let component = null
          const route = this.$router.$options.routes.find(route => route.path === this.$router.current)
          if (route) component = route.component
          return h(component)
          // return h('div', 'router-view')
        }
      })
    }
  })
}

export default KVueRouter
